package com.spy.system.service.impl;


import com.spy.system.domain.SysSupplierDelivery;
import com.spy.system.mapper.SysSupplierDeliveryMapper;
import com.spy.system.service.ISysSupplierDeliveryService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 供应商供货明细Service实现类
 */
@Service
public class SysSupplierDeliveryServiceImpl implements ISysSupplierDeliveryService {

    // 注入Mapper
    @Autowired
    private SysSupplierDeliveryMapper deliveryMapper;

    // 1. 实现“根据供应商ID查供货明细”
    @Override
    public List<SysSupplierDelivery> getDeliveryListBySupplierId(Long supplierId) {
        return deliveryMapper.selectDeliveryListBySupplierId(supplierId);
    }

    // 2. 实现“统计供应商供货占比”
    @Override
    public Map<String, BigDecimal> getSupplierDeliveryRatio(String timeRange) {
        Date startTime = getStartTimeByTimeRange(timeRange);
        List<Map<String, Object>> ratioList = deliveryMapper.selectDeliveryRatio(startTime);

        // 第一步：计算所有供应商的总采购量
        BigDecimal totalAllQuantity = BigDecimal.ZERO;
        for (Map<String, Object> item : ratioList) {
            // 累加所有供应商的采购量，得到总和
            totalAllQuantity = totalAllQuantity.add((BigDecimal) item.get("totalQuantity"));
        }

        // 第二步：计算每个供应商的占比（采购量 ÷ 总采购量 × 100%）
        Map<String, BigDecimal> ratioMap = new HashMap<>();
        for (Map<String, Object> item : ratioList) {
            String supplierName = (String) item.get("supplierName");
            BigDecimal supplierQuantity = (BigDecimal) item.get("totalQuantity");

            // 避免总采购量为0时的除法错误
            BigDecimal percentage;
            if (totalAllQuantity.compareTo(BigDecimal.ZERO) == 0) {
                percentage = BigDecimal.ZERO;
            } else {
                // 计算占比（保留2位小数，四舍五入）
                percentage = supplierQuantity
                        .divide(totalAllQuantity, 4, BigDecimal.ROUND_HALF_UP) // 先保留4位小数，保证精度
                        .multiply(new BigDecimal("100")) // 乘以100，转成百分比
                        .setScale(2, BigDecimal.ROUND_HALF_UP); // 最终保留2位小数
            }

            ratioMap.put(supplierName, percentage); // 存入占比（百分比）
        }
        return ratioMap;
    }

    // 辅助方法：根据时间范围计算起始时间（不用改）
    private Date getStartTimeByTimeRange(String timeRange) {
        Calendar calendar = Calendar.getInstance();
        // 默认近1月
        if (timeRange == null || timeRange.isEmpty()) {
            calendar.add(Calendar.MONTH, -1);
        } else {
            switch (timeRange) {
                case "近1月":
                    calendar.add(Calendar.MONTH, -1);
                    break;
                case "近2月":
                    calendar.add(Calendar.MONTH, -2);
                    break;
                case "近3月":
                    calendar.add(Calendar.MONTH, -3);
                    break;
                default:
                    calendar.add(Calendar.MONTH, -1);
            }
        }
        return calendar.getTime();
    }
}